<template>
  <div>
    <div
      class="d-flex justify-space-between align-center py-4 border-b"
      :class="{ pointer: item.subscribe_type === SUB_TYPE.CREATOR }"
      v-for="item in items"
      :key="item.id"
      @click="toCreatorPage(item.username, item.author_aff, item.subscribe_type)"
    >
      <div class="d-flex align-center">
        <Avatar
          v-if="item.subscribe_type === SUB_TYPE.CREATOR"
          :src="item.avatar"
          :radius="25"
          :vip="item.is_vip"
          class="me-2"
          :class="{ pointer: item.subscribe_type === SUB_TYPE.CREATOR }"
        ></Avatar>
        <div v-else class="subscript-vip-avatar me-2">
          <img src="/images/premium/avatar-subscript.png" alt="Subscript Premium Member" />
        </div>
        <div class="d-flex flex-column line-height-140 font-size-14">
          <div>{{ item.nickname }}</div>
          <div class="text-subtitle letter-space-2">
            ＠{{ item.subscribe_type !== SUB_TYPE.CREATOR ? userData.username : item.username }}
          </div>
          <div
            class="text-subtitle line-height-120 font-size-12 pt-2"
            :class="{ 'd-none': item.subscribe_type !== SUB_TYPE.CREATOR }"
          >
            {{ formatPost(item.post) }}{{ $t('info.perPost') }} · {{ formatPost(item.subscribe)
            }}{{ $t('info.follower') }}
          </div>
          <div class="text-subtitle line-height-120 font-size-12 pt-2">
            {{
              item.auto_renewal === AUTO_RENEWAL.SINGLE_SUB && item.status === SUB_STATUS.RE_SUB
                ? $t('info.subAt')
                : $t('info.subIn')
            }}
            {{ formatDate(item.vip_time) }}
            {{ renewalStatus(item).value }}
          </div>
        </div>
      </div>
      <div
        v-if="
          !(
            item.auto_renewal === AUTO_RENEWAL.SINGLE_SUB &&
            (item.status === SUB_STATUS.CANCEL_SUB || item.status === SUB_STATUS.RESTORE_SUB)
          )
        "
        @click.stop="
          onSubStatus(
            item.author_aff,
            item.status,
            item.avatar,
            item.nickname,
            item.subscribe_price,
            item.username,
            item.subscribe_type,
            item.auto_renewal,
          )
        "
        class="primary-btn d-flex justify-center align-center"
        :class="{
          'primary-btn': item.status === SUB_STATUS.CANCEL_SUB,
          'cancel-light-btn': item.status === SUB_STATUS.RESTORE_SUB,
          'primary-gradient': item.status === SUB_STATUS.RE_SUB,
        }"
      >
        {{
          item.status === SUB_STATUS.CANCEL_SUB
            ? $t('common.cancelSubscribe')
            : item.status === SUB_STATUS.RESTORE_SUB
            ? $t('common.restoreSubscribe')
            : $t('common.reSubscribe')
        }}
      </div>
    </div>
    <div v-if="!loading && items.length === 0" class="py-12">
      <ErrorNodata></ErrorNodata>
    </div>
    <div v-else>
      <v-container v-intersect="nextPage" class="text-center">
        <div v-if="loading" class="loading font-size-14 font-weight-400 line-height-140 text-center">
          {{ $t('common.loading') }}
        </div>
        <div v-if="noMore" class="no-more font-size-14 font-weight-400 line-height-140 text-center">
          {{ $t('common.noMore') }}
        </div>
      </v-container>
    </div>
  </div>
</template>
<script setup>
import { computed, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAdDialogStore } from '@/store/ad-dialog'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import ErrorNodata from '@/components/common/ErrorNodata.vue'
import Avatar from '@/components/multimedia/Avatar.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { useDialog } from '@/compositions/viewer/dialog'
import { AUTO_RENEWAL, POPUP_AD_DIALOG, SUB_STATUS, SUB_TYPE, VIP_STATUS } from '@/constant'
import API from '@/http'

const accountStore = useAccountStore()
const { userData, isVip } = storeToRefs(accountStore)

const renewalStatus = (item) => {
  return computed(() => {
    if (item.auto_renewal === AUTO_RENEWAL.SINGLE_SUB && item.status === SUB_STATUS.RE_SUB) {
      return $t('info.beExpired')
    } else if (item.auto_renewal === AUTO_RENEWAL.SINGLE_SUB || item.status === SUB_STATUS.RESTORE_SUB) {
      return $t('info.expiration')
    } else {
      return $t('info.renew')
    }
  })
}

const { open } = usePopupMessageStore()
const emits = defineEmits(['toPage'])

const {
  dataList: items,
  loading,
  noMore,
  errorMsg,
  init,
  refresh,
  nextPage,
} = useInfinite({ request: API.Auth.getsubscribelist })

init()

const { $confirm } = usePopupDialogStore()
const { subscribe } = useDialog()
const { $openAdDialog } = useAdDialogStore()

const onSubStatus = (sub, status, avatar, nickname, price, username, type, auto_renewal) => {
  if (type === SUB_TYPE.CREATOR) {
    if (status === SUB_STATUS.CANCEL_SUB) {
      const cancelSubOptions = {
        title: $t('common.cancelSubscribe'),
        content: $t('content.subStatus.cancelSub'),
        confirm: async () => {
          try {
            await API.Home.cancelSubscribe({ data: { author_aff: sub } })
            refresh()
          } catch (e) {
            console.log(e)
            open($t('common.cancelSubscribe') + $t('message.failure'))
          }
        },
        cancel: () => {
          console.log('按下取消')
        },
      }
      $confirm(cancelSubOptions).open()
    } else {
      subscribe({
        item: {
          author: {
            aff: sub,
            avatar,
            nickname,
            username,
            price,
          },
        },
      })
    }
  } else {
    if (auto_renewal === AUTO_RENEWAL.MONTH_SUB) {
      if (status === SUB_STATUS.CANCEL_SUB) {
        const cancelVipOptions = {
          title: $t('common.cancelSubscribe'),
          content: $t('content.subStatus.cancelSub'),
          confirm: async () => {
            try {
              await API.Home.setVipStatus({ data: { type: VIP_STATUS.CANCEL_SUB } })
              refresh()
            } catch (e) {
              console.log(e)
              open($t('common.cancelSubscribe') + $t('message.failure'))
            }
          },
          cancel: () => {
            console.log('按下取消')
          },
        }
        $confirm(cancelVipOptions).open()
      } else if (status === SUB_STATUS.RESTORE_SUB) {
        const restoreVipOptions = {
          title: $t('common.restoreSubscribe'),
          content: $t('content.subStatus.restoreSub'),
          confirm: async () => {
            try {
              await API.Home.setVipStatus({ data: { type: VIP_STATUS.RESTORE_SUB } })
              refresh()
            } catch (e) {
              console.log(e)
              open($t('common.restoreSubscribe') + $t('message.failure'))
            }
          },
          cancel: () => {
            console.log('按下取消')
          },
        }
        $confirm(restoreVipOptions).open()
      } else {
        $openAdDialog(POPUP_AD_DIALOG.PREMIUM).open()
      }
    } else {
      $openAdDialog(POPUP_AD_DIALOG.PREMIUM).open()
    }
  }
}

function toCreatorPage(username, id, type) {
  if (type === SUB_TYPE.CREATOR) {
    emits('toPage', 'another-creator', [id, username, 'purchases'])
  }
}

const formatDate = (date) => {
  return date.slice(0, 10)
}
const formatPost = (post) => {
  return post.toLocaleString()
}

watch(
  () => isVip.value,
  (newValue) => {
    if (newValue) {
      refresh()
    }
  },
)
</script>

<style lang="scss" scoped>
.letter-space-2 {
  letter-spacing: 0.2px;
}
.primary-btn {
  height: fit-content;
  padding: 0.375rem 1rem;
}
.subscript-vip-avatar {
  width: 3.125rem;
  height: 3.125rem;
  border-radius: 3.125rem;
  width: 3.125rem;
  height: 3.125rem;
  border-radius: 3.125rem;
  img {
    object-fit: cover;
    width: 100%;
    height: 100%;
    border-radius: inherit;
  }
}
</style>
